package com.deepconv.abbebot.xread;


import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.view.MenuItem;
import android.view.SurfaceView;
import android.view.WindowManager;

import com.deepconv.abbebot.xread.network.OkHttpClientManager;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.callback.StringCallback;
import com.lzy.okgo.model.Response;

import org.opencv.android.BaseLoaderCallback;
import org.opencv.android.CameraBridgeViewBase;
import org.opencv.android.CameraBridgeViewBase.CvCameraViewFrame;
import org.opencv.android.CameraBridgeViewBase.CvCameraViewListener2;
import org.opencv.android.LoaderCallbackInterface;
import org.opencv.android.OpenCVLoader;
import org.opencv.core.Mat;

import java.io.IOException;

public class MainActivity extends Activity implements CvCameraViewListener2 {

    // Used to load the 'native-lib' library on application startup.
    static {
        System.loadLibrary("native-lib");
    }

    private static final String TAG = "OCVSample::Activity";

    private CameraBridgeViewBase mOpenCvCameraView;
    private boolean mIsJavaCamera = true;
    private MenuItem mItemSwitchCamera = null;


    private BaseLoaderCallback mLoaderCallback = new BaseLoaderCallback(this) {
        @Override
        public void onManagerConnected(int status) {
            switch (status) {
                case LoaderCallbackInterface.SUCCESS: {
                    Log.i(TAG, "OpenCV loaded successfully");
                    mOpenCvCameraView.enableView();
                }
                break;
                default: {
                    super.onManagerConnected(status);
                }
                break;
            }
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
        setContentView(R.layout.tutorial1_surface_view);

        // Example of a call to a native method
        //TextView tv = (TextView) findViewById(R.id.sample_text);
        //tv.setText(stringFromJNI());
        mOpenCvCameraView = (CameraBridgeViewBase) findViewById(R.id.tutorial1_activity_java_surface_view);

        mOpenCvCameraView.setVisibility(SurfaceView.VISIBLE);

        mOpenCvCameraView.setCvCameraViewListener(this);
        mOpenCvCameraView.enableView();
        FindObjectInit();
        OkGo.getInstance().init(getApplication());
    }

    /**
     * A native method that is implemented by the 'native-lib' native library,
     * which is packaged with this application.
     */
    //public native String stringFromJNI();
    public static native int FindObjectInit();//绘本阅读初始化

    public static native int FeatureCompute(long mat);//提取图片的特征点

    @Override
    public void onPause() {
        super.onPause();
        if (mOpenCvCameraView != null)
            mOpenCvCameraView.disableView();
    }

    @Override
    public void onResume() {
        super.onResume();
        if (!OpenCVLoader.initDebug()) {
            Log.d(TAG, "Internal OpenCV library not found. Using OpenCV Manager for initialization");
            OpenCVLoader.initAsync(OpenCVLoader.OPENCV_VERSION_3_0_0, this, mLoaderCallback);
        } else {
            Log.d(TAG, "OpenCV library found inside package. Using it!");
            mLoaderCallback.onManagerConnected(LoaderCallbackInterface.SUCCESS);
        }
    }

    public void onDestroy() {
        super.onDestroy();
        if (mOpenCvCameraView != null)
            mOpenCvCameraView.disableView();
    }

    @Override
    public void onCameraViewStarted(int i, int i1) {

    }

    @Override
    public void onCameraViewStopped() {

    }

    @Override
    public Mat onCameraFrame(CvCameraViewFrame inputFrame) {

        Mat inputMat = inputFrame.gray();

        org.opencv.core.Core.flip(inputMat, inputMat, 1);
        FeatureCompute(inputMat.nativeObj);

        //生成图像尺寸信息
        short height, width;
        height = (short) inputMat.rows();
        width = (short) inputMat.cols();
        byte[] size = new byte[4];
        size[0] = (byte) (height & 0xff);
        size[1] = (byte) (height >> 8 & 0xff);
        size[2] = (byte) (width & 0xff);
        size[3] = (byte) (width >> 8 & 0xff);

        byte[] grayData = new byte[height * width];
        inputMat.get(0, 0, grayData);

        byte[] imageData = new byte[size.length + height * width];
        System.arraycopy(size, 0, imageData, 0, size.length);
        System.arraycopy(grayData, 0, imageData, size.length, grayData.length);

        doBookCoverSearchPost(imageData, new StringCallback() {
            @Override
            public void onSuccess(Response<String> response) {
                Log.d(TAG, response.body());
            }
        });
//        String response_str = doBookCoverSearchPOST(imageData, null);
//        Log.d(TAG, "response=" + response_str);
        return inputMat;
    }

    //public final static String API_PROTOCOL = "https://";
//    public final static String BOOK_URL = "sxdc2018abbbook.abbebot.com";
    public final static String API_PROTOCOL = "http://";
    public final static String BOOK_URL = "192.168.51.228";
    public static final String BOOK_SEARCH_URL = API_PROTOCOL + BOOK_URL + "/search_book";

    public void doBookCoverSearchPost(byte[] bodyStr, StringCallback callback) {
        OkGo.<String>post(BOOK_SEARCH_URL)
                .tag(this)
                .upBytes(bodyStr)
                .execute(callback);
    }

    public String doBookCoverSearchPOST(byte[] bodyStr, Object tag) {
        String resBody = null;
        com.squareup.okhttp.Response response = OkHttpClientManager.postSyncOctetStream(BOOK_SEARCH_URL, bodyStr, tag);
        if (response != null) {
            try {
                resBody = response.body().string();
            } catch (IOException e) {
                resBody = "0";
            }
        } else {
            resBody = "0";
        }
        return resBody;
    }
}
